<template>
  <a-drawer
      title="自建线索"
      :width="$store.getters.isMobile ? 350 : 460"
      :visible="visible"
      :body-style="{ paddingBottom: '80px' }"
      @close="onClear"
      destroy-on-close
  >

    <a-form layout="vertical" ref="formRef" :rules="rulesRef" :model="modelRef">


      <template v-for="item in templateFields">
        <a-col :span="24" v-if="item.alias=='contact_name'">
          <a-form-item label="客户名称" name="contact_name">
            <a-input
                v-model:value="modelRef.contact_name"
                placeholder="请输入客户名称"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="item.alias=='contact_phone'">
          <a-form-item label="客户手机号" name="contact_phone">
            <a-input
                v-model:value="modelRef.contact_phone"
                placeholder="请输入客户手机号"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="item.alias=='company'">
          <a-form-item label="公司" name="company">
            <a-input
                v-model:value="modelRef.company"
                placeholder="请输入所属公司"
            />
          </a-form-item>
        </a-col>

        <a-col span="24" v-if="item.alias=='village_id'">
          <a-form-item label="意向项目" v-bind="validateInfos.build_ids">
            <a-cascader
                v-model:value="modelRef.build_ids"
                :options="optionsBuild"
                placeholder="请选择"
                @change="buildChange"
            />
          </a-form-item>
        </a-col>

        <a-col :span="24" v-if="item.alias=='expect_area'">
          <a-form-item label="需求面积段">
            <a-input-group size="default">
              <a-row :gutter="8">
                <a-col :span="8">
                  <a-input-number
                      v-model:value="modelRef.expect_area_min"
                      addon-after="m²"
                      placeholder="最小值"
                      :min="1"
                  />
                </a-col
                >
                -
                <a-col :span="8">
                  <a-input-number
                      addon-after="m²"
                      v-model:value="modelRef.expect_area_max"
                      placeholder="最大值"
                      :min="1"
                  />
                </a-col>
              </a-row>
            </a-input-group>
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="item.alias=='remark'">
          <a-form-item label="备注" name="remark">
            <a-textarea
                v-model:value="modelRef.remark"
                placeholder="请输入备注"
                :rows="4"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="item.alias=='source'">
          <a-form-item label="来源" name="source">
            <a-select :options="clueSource" v-model:value="modelRef.source"
                      @change="sourceChange"
                      placeholder="请选择来源"></a-select>
          </a-form-item>
        </a-col>

      </template>

      <template v-if="modelRef.source==7">
        <a-col :span="24">
          <a-form-item label="渠道类型" name="channel_type">
            <a-select
                v-model:value="modelRef.channel_type"
                :options="sourceOptions"
                placeholder="请选择渠道类型"
                @change="changeChannelSource"
            ></a-select>
          </a-form-item>
        </a-col>

        <a-col :span="24">
          <a-form-item label="所属公司" name="channel_company_id" v-if="is_company">
            <a-select
                v-model:value="modelRef.channel_company_id"
                :options="companyOptions"
                placeholder="所属公司"
                allowClear
                show-search
                :filter-option="filterCompanyOption"
                @change="companyChange"
            ></a-select>
          </a-form-item>
        </a-col>


      </template>

      <a-col :span="24">
        <a-form-item name="channel_id">
          <template #label>
            <span>关联渠道人员</span>
            <text-tip tips="关联渠道与意向项目关联，请先选择意向项目"/>
          </template>
          <a-select
              v-model:value="modelRef.channel_id"
              placeholder="请选择"
              :options="filterChannelList"
              @change="channelChange"
              show-search
              :filter-option="filterOption"
          >
          </a-select>
        </a-form-item>
      </a-col>
      <a-col :span="24" v-if="isManage&&is_have_team_id">
        <a-form-item label="跟进人员">
          <span>{{ team_user_name }}</span>
        </a-form-item>
      </a-col>

      <a-col :span="24" v-if="isManage&&!is_have_team_id">
        <a-form-item label="跟进人员">
          <a-radio-group v-model:value="modelRef.operate_type" size="small">
            <a-radio :value="1"
            ><span style="font-size: 12px">指定人员</span></a-radio
            >
            <a-radio :value="2"
            ><span style="font-size: 12px">加入公海</span></a-radio
            >
            <a-radio :value="3"
            ><span style="font-size: 12px">平均分配</span></a-radio
            >
            <a-radio :value="4"
            ><span style="font-size: 12px">分配给创建人</span></a-radio
            >
          </a-radio-group>
          <template v-if="modelRef.operate_type == 1">

            <a-cascader
                style="margin-top: 10px"
                v-model:value="modelRef.user_id"
                :options="groupOptions"
                :load-data="getTeamList"
                placeholder="选择分配人员"
            />
          </template>
        </a-form-item>
      </a-col>


      <template v-if="customFields.length">
        <a-form layout="vertical" ref="customForm" :model="customModelRef" :rules="customRulesRef">
          <a-col :span="24" v-for="(item,index) in customFields">

            <a-form-item v-if="item.field_type=='input'" :label="item.field_name"
                         :name="item.extra.key"
            >
              <a-input :placeholder="`请输入${item.field_name}`"
                       v-model:value="customModelRef[item.extra.key]"/>
            </a-form-item>
            <a-form-item v-if="item.field_type=='textarea'" :label="item.field_name"
                         :name="item.extra.key">
              <a-textarea :placeholder="`请输入${item.field_name}`"
                          v-model:value="customModelRef[item.extra.key]"/>
            </a-form-item>
            <a-form-item v-if="item.field_type=='singleSelect'" :label="item.field_name"
                         :name="item.extra.key">
              <a-select :placeholder="`请选择${item.field_name}`"
                        v-model:value="customModelRef[item.extra.key]"
                        :options="item.option"/>
            </a-form-item>
            <a-form-item v-if="item.field_type=='mutiSelect'" :label="item.field_name"
                         :name="item.extra.key">
              <a-select :placeholder="`请选择${item.field_name}`"
                        v-model:value="customModelRef[item.extra.key]"
                        :options="item.option" mode="multiple"/>
            </a-form-item>
            <a-form-item v-if="item.field_type=='image'" :label="item.field_name"
                         :name="item.extra.key"
            >
              <a-upload
                  :action="imgAction"
                  v-model:file-list="customModelRef[item.extra.key]"
                  :multiple="false"
                  accept="image/*"
                  name="image"
                  list-type="picture-card"
                  :headers="{ 'org-token': $store.getters.token }"
                  :data="{ dir: 'org_village' }"
                  @change="(info)=>handleUploadChange(info,index)"
              >
                <div v-if="item.extra.files.length < 6">
                  <PlusOutlined/>
                  <div style="padding-top: 4px">上传</div>
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item v-if="item.field_type=='file'" :label="item.field_name"
                         :name="item.extra.key"
            >
              <a-upload
                  :action="fileAction"
                  v-model:file-list="customModelRef[item.extra.key]"
                  :multiple="false"
                  :headers="{ 'org-token': $store.getters.token }"
                  :data="{ dir: 'org_village' }"
                  @change="(info)=>handleUploadChange(info,index)"

              >
                <div v-if="item.extra.files.length < 6">
                  <a-button>
                    <UploadOutlined/>
                    上传
                  </a-button>
                </div>
              </a-upload>
            </a-form-item>
          </a-col>
        </a-form>
      </template>


      <div
          :style="{
              position: 'absolute',
              right: 0,
              bottom: 0,
              width: '100%',
              borderTop: '1px solid #e9e9e9',
              padding: '10px 16px',
              background: '#fff',
              textAlign: 'right',
              zIndex: 1,
            }"
      >
        <a-button style="margin-right: 8px" @click="onClear">取消</a-button>
        <a-button type="primary" html-type="submit" @click="onSubmit"
        >提交
        </a-button
        >
      </div>
    </a-form>


  </a-drawer>
</template>

<script>
import {reactive, ref, toRefs, watch} from "vue";
import request from "../../../../common/utils/request";
import {Form, message} from "ant-design-vue";
import {TextTip} from "bl-common-vue3";
import store from "@/store";
import {PlusOutlined, UploadOutlined} from '@ant-design/icons-vue'
import utils from '@/common/utils/utils'

const useForm = Form.useForm;

export default {
  name: "CreateClue",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    clueSource: {
      type: Array,
      default: () => [],
    }
  },
  components: {PlusOutlined, TextTip, UploadOutlined},
  setup(props, context) {
    const state = reactive({
      idList: [],
      channelObject: {},
      isManage: false,
      is_have_team_id: false,
      team_user_name: "",
      is_company: false,
      filterChannelList: []
    });


    const templateFields = ref([])
    const modelRef = reactive({
      contact_name: "",
      contact_phone: "",
      company: "",
      build_ids: [],
      village_id: undefined,
      build_id: undefined,
      expect_area_min: "",
      expect_area_max: "",
      area: "",
      operate_type: 1,
      user_id: undefined,
      remark: "",
      source: undefined,

      channel_type: undefined,
      channel_company_id: undefined,
    })
    const rulesRef = reactive({
      contact_name: [
        {
          required: true,
          message: "请输入联系人姓名",
        },
      ],
      contact_phone: [
        {
          required: true,
          message: "请输入联系电话",
        },
      ],
      build_ids: [
        {
          required: true,
          message: "请选择意向项目",
        },
      ],
    })


    const {resetFields, validate, validateInfos} = useForm(
        modelRef,
        rulesRef
    );

    // 自定义相关
    const customForm = ref()
    const customFields = ref([])
    const customModelRef = reactive({})
    const customRulesRef = reactive({})

    //1招商领导 2招商专员
    const getRole = () => {
      request
          .get("/org", "/business/customerTeam/UserRoleInfo", {village_id: modelRef.village_id})
          .then((res) => {
            let level = store.getters.userInfo.level;
            if (res.role == 1 || level == 99) {
              state.isManage = true;
            } else {
              state.isManage = false;
            }
          });
    };

    // 意向楼宇
    const optionsBuild = ref([]);
    const getSelectVillage = () => {
      return new Promise(resolve => {
        request.get("/org", "/business/customerTeam/getSelectVillage").then(res => {
          resolve(res.data)
        })
      })
    }

    const getBuildList = () => {
      getSelectVillage().then(ids => {
        request
            .get("/org", "/build/villageAndBuildList/v2", {checked: 1})
            .then((res) => {
              let vList = [];
              res.villageList.forEach((item) => {
                if (ids.includes(item.id)) {
                  vList.push({
                    label: item.name,
                    value: item.id,
                    children: item.buildList.map((childItem) => {
                      return {
                        label: childItem.build_name,
                        value: childItem.id,
                      };
                    }),
                  });
                }
              });
              optionsBuild.value = vList;
            });
      })
    }

    const groupOptions = ref([]);
    const getGroupList = () => {
      request.post("/org", "/business/customerTeam/list").then(res => {
        // console.log(res)
        groupOptions.value = res.list.map(item => {
          return {
            label: item.name,
            value: item.id,
            isLeaf: false,
          }
        })
      })
    }

    const getTeamList = (selectedOptions) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      // console.log(targetOption)
      request.get("/org", "/business/customerTeam/teamUserIndex", {team_id: targetOption.value}).then(res => {
        console.log(res)
        targetOption.loading = false;
        targetOption.children = [];
        targetOption.children = res.data.map(item => {
          return {
            label: item.name,
            value: item.uid
          }
        })
        groupOptions.value = [...groupOptions.value];
      });
    }


    // 获取渠道列表
    const channelList = ref([]);
    const getChannelList = () => {
      const key = "channel" + modelRef.village_id;
      modelRef.channel_id = undefined;
      if (Object.keys(state.channelObject).includes(key)) {
        channelList.value = state.channelObject[key];
        setFilterChannel()
      } else {
        request
            .get("/org", "/business/customer/channel/index", {
              village_id: modelRef.village_id,
            })
            .then((res) => {
              const list = res.list.map((item) => {
                return {
                  ...item,
                  value: item.id,
                  label: item.name,
                };
              });
              channelList.value = list;
              state.channelObject[key] = list;
              setFilterChannel();
            });
      }
    };

    const getDefaultField = () => {
      const params = {
        is_root: 1,
      }
      request.get("/org", "/business/clueField/getClueDiyField", params).then(res => {
        templateFields.value = res.data
      })

    }
    // 获取自定义的配置信息
    const getOtherFieldInfo = (val) => {
      const params = {
        is_root: 0,
      }
      params.village_id = modelRef.village_id;
      request.get("/org", "/business/clueField/getClueDiyField", params).then(res => {
        customFields.value = res.data;
        console.log(customFields.value)
        customFields.value.forEach(item => {
          let msg = ""
          if (item.field_type == 'input' || item.field_type == 'textarea') {
            msg = "请输入"
          } else if (item.field_type == 'singleSelect' || item.field_type == 'mutiSelect') {
            msg = "请选择"
          } else if (item.field_type == 'image' || item.field_type == 'file') {
            msg = "请上传"
          }
          customRulesRef[item.extra.key] = [
            {
              required: item.is_required == 1,
              message: `${msg}${item.field_name}`,
              trigger: "change"
            }
          ]
        })

        customFields.value.forEach(item => {
          if (item.type == 'input' || item.type == 'texearea') {
            customModelRef[item.extra.key] = item.extra.content;
          } else if (item.type == 'singleSelect') {
            customModelRef[item.extra.key] = item.extra.selectOption;
          } else if (item.type == 'mutiSelect') {
            customModelRef[item.extra.key] = item.extra.selectOptions;
          } else if (item.type == 'image' || item.type == 'file') {
            customModelRef[item.extra.key] = item.extra.files;
          }
        })
      })

    }
    const buildChange = (value) => {
      state.isManage = false
      if (value?.length > 0) {
        modelRef.village_id = value[0];
        getOtherFieldInfo(value[1]);
        getChannelList();
        getRole()
      }
    };

    const init = () => {
      getBuildList();
      getGroupList()
      getDefaultField();
      getCompanyList();
      getChannelSourceList();

    };

    const changeFormat = () => {

      const newArray = []
      for (let i = 0; i < customFields.value.length; i++) {
        const item = customFields.value[i]
        const value = {};
        if (item.field_type.startsWith("input")) {
          value.type = "input"
          value.content = customModelRef[item.extra.key]
          value.name = item.field_name
        } else if (item.field_type.startsWith("textarea")) {
          value.type = "textarea"
          value.content = customModelRef[item.extra.key]
          value.name = item.field_name
        } else if (item.field_type.startsWith("singleSelect")) {
          value.type = "singleSelect"
          value.content = customModelRef[item.extra.key]
          value.name = item.field_name
        } else if (item.field_type.startsWith("mutiSelect")) {
          value.type = "mutiSelect"
          value.content = customModelRef[item.extra.key]
          value.name = item.field_name
        } else if (item.field_type.startsWith("image")) {
          value.type = "image"
          value.content = customModelRef[item.extra.key]?.map(file => {
            return {
              url: file.url,
              name: file.name
            }
          })
          value.name = item.field_name
        } else if (item.field_type.startsWith("file")) {
          value.type = "file"
          value.content = customModelRef[item.extra.key]?.map(file => {
            return {
              url: file.url,
              name: file.name
            }
          })
          value.name = item.field_name
        }
        newArray.push(value)
      }

      return newArray
    }

    const channelChange = (e) => {
      const items = channelList.value.filter(item => {
        return item.id == e
      })
      if (items.length == 1) {
        const item = items[0]
        console.log(item)
        if (item.team_user_id > 0) {
          state.is_have_team_id = true;
          modelRef.user_id = item.team_user_id
          state.team_user_name = item.team_user_name
        } else {
          state.is_have_team_id = false;
          modelRef.user_id = undefined
          state.team_user_name = ""
        }
      }
    }


    const submit = () => {
      if (modelRef.operate_type == 1 && modelRef.user_id == undefined && state.isManage) {
        message.error("请选择分配人员")
        return
      }

      if (modelRef.build_ids.length > 0) {
        console.log(modelRef.build_ids);
        modelRef.village_id = modelRef.build_ids[0];
        modelRef.build_id =
            modelRef.build_ids.length > 1 ? modelRef.build_ids[1] : undefined;
      }

      if (modelRef.source != 7) {
        delete modelRef.channel_type;
        delete modelRef.channel_company_id;
      }
      if (!state.is_company) {
        delete modelRef.channel_company_id;
      }
      const params = {
        ...modelRef,
        diy_field: changeFormat()
      };
      if (modelRef.operate_type == 1 && modelRef?.user_id?.length > 1) {
        params.user_id = modelRef.user_id[1];
      }
      if (!state.isManage) {
        params.operate_type = 0;
      }
      if (state.is_have_team_id) {
        delete params.operate_type;
      }
      delete params.build_ids;
      console.log(params);
      request.post("org", "/business/clue", params).then((res) => {
        message.success(res.msg || "提交成功");
        context.emit("ok");
      });
    }

    // 提交
    const onSubmit = () => {
      validate().then(() => {
        console.log(customFields.value)
        if (customFields.value.length > 0) {
          customForm.value.validateFields().then(() => {
            submit()
          }).catch((e) => {
            console.log(e)
          })
        } else {
          submit();
        }
      })
    };

    const onClear = () => {
      context.emit("onClose");
    };

    watch(
        () => props.visible,
        (val) => {
          if (val == true) {
            init();
          } else {
            resetFields();
            modelRef.channel_id = undefined;
            modelRef.user_id = undefined;
            state.channelObject = {};
            channelList.value = [];
            state.filterChannelList = [];
            state.list = [];
            state.itemList = [];
            state.idList = [];
            customFields.value = [];
            for (const key in customModelRef) {
              customModelRef[key] = undefined
            }
            for (const key in customRulesRef) {
              customRulesRef[key] = []
            }

          }
        }
    );

    const handleUploadChange = (info, index) => {

      const item = customFields.value[index]
      console.log(item)
      let resFileList = [...info.fileList];
      if (resFileList.length > 0) {
        resFileList = resFileList.slice(-1);
        resFileList = resFileList.map((file) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
              // fileList.value.push({
              //   name: file.name,
              //   url: file.fileUrl,
              // });
            } else {
              message.warning(file.response.msg);
            }
          }
          return file;
        });

      }

    }

    const sourceChange = (e) => {
      if (e != 7) {
        modelRef.channel_type = undefined
        modelRef.channel_company_id = undefined
        setFilterChannel()
      }
    }

    const changeChannelSource = (val, option) => {
      state.is_company = option.is_company
      if (!option.is_company) {
        modelRef.channel_company_id = undefined
        setFilterChannel()
      }
    }

    const companyOptions = ref([])
    const getCompanyList = () => {
      request.get("/org", "/user/channel/channelCompanyIndex").then(res => {

        companyOptions.value = res.data.map(item => {
          const is_expire = item.is_expire_txt == true
          return {
            label: is_expire ? `${item.name} (协议到期)` : item.name,
            value: item.id,
            disabled: is_expire,
            ...item
          }
        })
      })
    }

    // 渠道类型
    const sourceOptions = ref([]);
    const getChannelSourceList = () => {
      request
          .get("/org", "/business/customer/channel/sourceList")
          .then((res) => {
            sourceOptions.value = res.list.map((item) => {
              return {
                value: item.id,
                label: item.source,
                is_company: item.is_company == 1 ? true : false
              };
            });
          });
    };
    const filterOption = (input, option) => {
      return option.name.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    };

    const filterCompanyOption = (string, any) => {
      return any.label.toLowerCase().indexOf(string.toLowerCase()) >= 0;
    };

    const companyChange = (value) => {
      modelRef.channel_company_id = value
      modelRef.channel_id = undefined
      setFilterChannel()
    }

    const setFilterChannel = () => {
      state.filterChannelList = modelRef.channel_company_id ? channelList.value.filter(item => {
        console.log(item)
        return item.channel_company_id == modelRef.channel_company_id
      }) : channelList.value
    }

    return {
      ...toRefs(state),
      onClear,
      onSubmit,
      modelRef,
      rulesRef,
      validateInfos,
      optionsBuild,
      channelList,
      getChannelList,
      buildChange,
      getGroupList,
      groupOptions,
      getTeamList,
      channelChange,
      customFields,
      customForm,
      customModelRef,
      customRulesRef,
      handleUploadChange,
      templateFields,
      imgAction: request.BASE_URL + "/public/system/uploadImage",
      fileAction: request.BASE_URL + "/public/system/uploadFile",
      changeChannelSource,
      companyOptions,
      sourceOptions,
      filterOption,
      sourceChange,
      filterCompanyOption,
      companyChange,


    };
  },
};
</script>

<style lang="less" scoped>
.user-tag :deep(.ant-tag) {
  border-radius: 20px !important;
  padding: 0 12px 0 0 !important;
  background: #f1f1f1;
  border: none;
}
</style>
